document.addEventListener('DOMContentLoaded', function () {
    const deleteButtons = document.querySelectorAll('.action-item.clear');
    deleteButtons.forEach(function (deleteButton) {
        deleteButton.addEventListener('click', function () {
            const article = this.closest('.video');
            if (article) {
                article.remove();
            }
        });
    });

    //改头像;
// 获取相关元素
    const img = document.getElementById('img');
    const photoEdit = document.getElementById('photo-edit');
    const fileInput = document.querySelector('.file');
    const imgElement = document.getElementById('uimg');

// 为图片和“修改我的头像”区域绑定点击事件
    img.addEventListener('click', function () {
        fileInput.click();
    });

    photoEdit.addEventListener('click', function () {
        fileInput.click();
    });

// 选择图片并上传
    fileInput.addEventListener('change', function (e) {
        const file = this.files[0];
        if (file) {
            // 预览图片
            const imgurl = window.URL || window.webkitURL;
            const newImg = new Image();
            newImg.onload = function () {
                imgElement.src = this.src;
                imgurl.revokeObjectURL(this.src);
            };
            newImg.src = imgurl.createObjectURL(file);
            console.log(13);
            // 上传图片到后端
            uploadAvatar(file);
            console.log(14);
        }
    });
// 执行上传的函数
    function uploadAvatar(file) {
        const formData = new FormData();
        formData.append('file', file);
        console.log(31);
        $.ajax({
            url: '/userHomepage/updateAvatar',
            type: 'POST',
            data: formData,
            processData: false, // 重要：不处理数据
            contentType: false, // 重要：不设置内容类型
            success: function (response) {
                showCustomAlert('头像上传成功');
                // 可以在这里更新页面上的头像显示
            },
            error: function (error) {
                console.error('上传失败:', error);
                showCustomAlert('上传失败，请重试');
            }
        });
    }
});

const mask=document.querySelector('.mask')
const titleInput = document.getElementById('titleInput');
const titleCharCount = document.getElementById('titleCharCount');
const contentTextarea = document.getElementById('contentTextarea');
const contentCharCount = document.getElementById('contentCharCount');
const closeButton = document.getElementById('closeButton');


// 获取所有的 "read-full-text" 元素和 "top-story-content-detail-list-p" 元素
const read_full_texts = document.getElementsByClassName('read-full-text');
const top_story_content_detail_list_ps = document.getElementsByClassName('empty');

// 遍历所有的 "read-full-text" 元素并添加点击事件监听器
for (let i = 0; i < read_full_texts.length; i++) {
    read_full_texts[i].addEventListener('click', function() {
        const index = Array.from(read_full_texts).indexOf(this);
        const targetParagraph = top_story_content_detail_list_ps[index];
        const user_information=document.getElementsByClassName('user-information')[index];
        const empty=document.getElementsByClassName('empty')[index]
        const user_name=document.getElementsByClassName('user-name')[index]
        const contentright=contentrights[index]
        const top_story_content_detail_list=top_story_content_detail_lists[index]
        // 使用 window.getComputedStyle 获取元素的实际样式
        const currentHeight = window.getComputedStyle(targetParagraph).height;
        if (currentHeight === '49px') {
            targetParagraph.style.height = 'auto';
            targetParagraph.style.display= 'block';
            user_information.style.display='block';
            user_name.style.display='none'
            empty.classList.add('content')
            contentright.style.display='none'
            console.log(contentright.style.display)
            console.log( user_information.style.display)
            console.log(1)
            top_story_content_detail_list.style.width='100%'
            this.innerHTML = '<i class="iconfont">&#xe60d;</i>收起<i class="iconfont">&#xe6b8;</i>';
        } else {
            targetParagraph.style.height = '49px';
            this.innerHTML = '<i class="iconfont">&#xe60d;</i>阅读全文<i class="iconfont">&#xe7d1;</i>';
            targetParagraph.style.display= '-webkit-box';
            user_information.style.display='none';
            user_name.style.display='inline';
            empty.classList.remove('content')
            contentright.style.display='block'
            top_story_content_detail_list.style.width='74%'
        }
    });
}


const contentrights=document.getElementsByClassName('content-right')
const top_story_content_detail_lists=document.getElementsByClassName('top-story-content-detail-list')



function showCustomAlert(message, duration) {
    let customAlert = document.getElementById('customAlert');
    if (!customAlert) {
        div_outter=document.createElement('div');
        customAlert = document.createElement('div');
        customAlert.id = 'customAlert';
        // customAlert.style.margin='7px 12px';
        const alertMessage = document.createElement('p');
        alertMessage.id = 'alertMessage';
        customAlert.appendChild(alertMessage);

        document.body.appendChild(customAlert);
    }

    const alertMessage = document.getElementById('alertMessage');

    alertMessage.textContent = message;
    if(alertMessage.textContent==null){
        customAlert.style.display = 'none';
    }

    customAlert.style.display = 'block';
    setTimeout(() => {
        customAlert.style.display = 'none';
    }, duration);
}


let top_story_content_footer_button_likes=document.getElementsByClassName('top-story-content-footer-button-like')
let likes=document.getElementsByClassName('like')
for (let i = 0; i < top_story_content_footer_button_likes.length; i++) {
    top_story_content_footer_button_likes[i].addEventListener('click', function () {


        let like_value=top_story_content_footer_button_likes[i].value
        const postIdNum = Number(like_value);
        console.log(postIdNum)
        console.log(window.getComputedStyle(top_story_content_footer_button_likes[i]).color)
        if (window.getComputedStyle(top_story_content_footer_button_likes[i]).color === 'rgba(169, 178, 185, 0.937)') {

            $.ajax({
                url: `/posts/like?postId=${like_value}`,

                type: 'POST',
                data: {postId: postIdNum},
                success: function (result) {
                    showCustomAlert('点赞成功', 3000)
                    top_story_content_footer_button_likes[i].style.color= 'rgba(255,0,0,1)'
                    likes[i].style.color= 'rgba(255,0,0)'
                    console.log('发送点赞请求到:', this.url);
                },
                error: function (error) {
                    showCustomAlert('点赞失败: ' + error.status + ' ' + error.statusText, 3000);
                    console.log(error);
                    console.log('发送点赞请求到:', this.url);
                }

            })

        }else {
            console.log(1111111)
            $.ajax({
                url: `/posts/cancelLike?postId=${like_value}`,

                type: 'POST',
                data: {postId: postIdNum},
                success: function (result) {
                    showCustomAlert('取消点赞', 3000)
                    top_story_content_footer_button_likes[i].style.color = 'rgba(169, 178, 185, 0.937)'
                    likes[i].style.color= 'rgba(169, 178, 185, 0.937)'
                    console.log('发送点赞请求到:', this.url);
                },
                error: function (error) {
                    showCustomAlert('取消点赞失败: ' + error.status + ' ' + error.statusText, 3000);
                    console.log(error);
                    console.log('发送点赞请求到:', this.url);
                }

            })
        }

    })
}
let personalMainPage=document.getElementsByClassName('personalMainPage')[0]
console.log(personalMainPage)
personalMainPage.addEventListener('click',()=>{
    event.preventDefault();
    window.location.href='http://localhost:8080/userHomepage'
})
function articleDetail(postId) {

    console.log( postId)
    const postIdNum = Number(postId);
    $.ajax({
        url: `/postsComments?postId=${postIdNum}`,
        type: 'GET',

        success: function (result) {

            console.log(result)

            let commentListHTML = '';
            const comments = result.comments;
            const commentUsers = result.commentUsers;

            for (let i = 0; i < comments.length; i++) {

                const commentUser = commentUsers[i];
                console.log('commentUser.avatar:', commentUser.avatar);
                console.log('commentUser.username:', commentUser.username);
                console.log('comments[i].content:', comments[i].content);
                console.log('comments[i].createdAt:', comments[i].createdAt);
                commentListHTML += `
                    <div class="comment-item" style="padding-top: 10px;">
                        <div class="comment-user">
                            <img src="${commentUser.avatar}" alt="用户头像" class="avatar">
                            <span class="username">${commentUser.username}</span>
                        </div>
                        <div class="comment-content">
                            <p>${comments[i].content}</p>
                            <span class="comment-time">${comments[i].createdAt}</span>
                        </div>
                        <div class="comment-actions">
                            <span class="reply-icon">💬 回复</span>
                        </div>
                    </div>
                `;
            }

            const comment_item_outer = document.getElementsByClassName('comment-item-outer')[0];
            comment_item_outer.innerHTML += commentListHTML;

        },
        error: function (error) {

            console.log(error);
        }
    })

}

let comments=document.getElementsByClassName('comment-publish')
let top_story_content_footer_button_starts=document.getElementsByClassName('top-story-content-footer-button-start')
for(let i=0;i<top_story_content_footer_button_starts.length;i++){
    top_story_content_footer_button_starts[i].addEventListener('click',()=>{
        if( top_story_content_footer_button_starts[i].innerHTML.includes('收起评论')){
            comments[i].style.display='none'
            let value=top_story_content_footer_button_starts[i].value
            top_story_content_footer_button_starts[i].innerHTML=`<i class="iconfont comment" >&#xe619;</i> ${value}条评论`
        }else{
            top_story_content_footer_button_starts[i].innerHTML=`<i class="iconfont comment" >&#xe619;</i> 收起评论`
            comments[i].style.display='block'
        }





    })
}
document.addEventListener('DOMContentLoaded', function() {
    const pathname = window.location.pathname;
    let temp = 0;
    if (pathname === '/mainPageRecommend') {
        temp = 1

        document.getElementsByClassName('none-input')[0].value = temp
    } else if (pathname === '/mainPageAttention') {
        temp = 2
        document.getElementsByClassName('none-input')[0].value = temp
    } else if (pathname === '/mainPageTrending') {
        temp = 3
        document.getElementsByClassName('none-input')[0].value = temp
    }
})
function publish(postId){
    const postIdNum = Number(postId);
    let content=document.getElementsByClassName('comment-input-detail')[0].value
    let comment_input_detail=document.getElementsByClassName('comment-input-detail')[0]
    $.ajax({
        url:  `/posts/comment?content=${content}&postId=${postId}`,

        type: 'POST',
        data: {postId:postIdNum,
            content:content},


        success: function(result){

            showCustomAlert('评论成功',3000)
            console.log(result);
            comment_input_detail.value=' '
            let commentListHTML = '';
            const comments = result.commentList;
            const commentUsers = result.userList;
            for (let i = 0; i < comments.length; i++) {
                const commentUser = commentUsers[i];
                top_story_content_footer_button_starts[i].innerHTML=`<i class="iconfont comment" >&#xe619;</i> ${result.commentsCount}条评论`
                commentListHTML += `
                    <div class="comment-item" style="padding-top: 10px;">
                        <div class="comment-user">
                            <img src="${commentUser.avatar}" alt="用户头像" class="avatar">
                            <span class="username">${commentUser.username}</span>
                        </div>
                        <div class="comment-content">
                            <p>${comments[i].content}</p>
                            <span class="comment-time">${comments[i].createdAt}</span>
                        </div>
                        <div class="comment-actions">
                            <span class="reply-icon">💬 回复</span>
                        </div>
                    </div>
                `;
            }

            const comment_item_outer = document.getElementsByClassName('comment-item-outer')[0];
            comment_item_outer.innerHTML = commentListHTML;
        },
        error:function(error){
            showCustomAlert('评论失败: ' + error.status + ' ' + error.statusText, 3000);
            console.log(error);

        }

    })
}
let wait_answer=document.getElementsByClassName('wait-answer')[0]
console.log(wait_answer)
wait_answer.addEventListener('click',()=>{
    event.preventDefault();
    window.location.href='/thoughtMainPage'
})
let mainPage=document.getElementsByClassName('mainPage')[0]
mainPage.addEventListener('click',()=>{
    event.preventDefault();
    window.location.href='http://localhost:8080/mainPageRecommend'
})
var menu_text=document.getElementsByClassName('menu-text')[0]
var user_text=document.getElementsByClassName('user-text')[0]
var favorites_text=document.getElementsByClassName('favorites-text')[0]
var notification_list=document.getElementsByClassName('notification-list')[0]
var notification_list2=document.getElementsByClassName('notification-list2')[0]
var menu_icon=document.getElementsByClassName('menu-icon')[0]
var user_icon=document.getElementsByClassName('user-icon')[0]
var favorites_icon=document.getElementsByClassName('favorites-icon')[0]
var none=document.getElementsByClassName('none')[0]
// menu_text.addEventListener('click',()=>{
//
//     notification_list.style.display='block'
//     notification_list2.style.display='none'
//     none.style.display='none'
//     menu_text.style.color='#ff9606'
//     menu_icon.style.color='#ff9606'
//     user_text.style.color='#495057'
//     user_icon.style.color='#495057'
//     favorites_text.style.color='#495057'
//     favorites_icon.style.color='#495057'
// })
// user_text.addEventListener('click',()=>{
//
//     notification_list.style.display='none'
//     notification_list2.style.display='block'
//     none.style.display='none'
//     user_text.style.color='#3487FF'
//     user_icon.style.color='#3487FF'
//     menu_text.style.color='#495057'
//     menu_icon.style.color='#495057'
//     favorites_text.style.color='#495057'
//     favorites_icon.style.color='#495057'
// })
// favorites_text.addEventListener('click',()=>{
//
//     notification_list.style.display='none'
//     notification_list2.style.display='none'
//     none.style.display='flex'
//     favorites_text.style.color='red'
//     favorites_icon.style.color='red'
//     menu_text.style.color='#495057'
//     menu_icon.style.color='#495057'
//     user_text.style.color='#495057'
//     user_icon.style.color='#495057'
// })
